package com.module.admin.prj.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.module.admin.BaseController;
import com.module.admin.prj.pojo.PrjInfo;
import com.module.admin.prj.pojo.PrjVersion;
import com.module.admin.prj.service.PrjInfoService;
import com.module.admin.prj.service.PrjVersionService;
import com.module.admin.sys.enums.SysFileType;
import com.module.admin.sys.pojo.SysUser;
import com.module.admin.sys.utils.SysFileUtil;
import com.module.comm.utils.JGitUtil;
import com.module.comm.utils.MavenUtil;
import com.system.comm.model.KvEntity;
import com.system.comm.utils.FrameFileUtil;
import com.system.comm.utils.FrameStringUtil;
import com.system.comm.utils.FrameTimeUtil;
import com.system.handle.model.ResponseCode;
import com.system.handle.model.ResponseFrame;

/**
 * prj_version的Controller
 * @author yuejing
 * @date 2016-10-19 15:55:36
 * @version V1.0.0
 */
@Controller
public class PrjVersionController extends BaseController {

	private static final Logger LOGGER = LoggerFactory.getLogger(PrjVersionController.class);

	@Autowired
	private PrjVersionService prjVersionService;
	@Autowired
	private PrjInfoService prjInfoService;
	
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		try {
			SimpleDateFormat dateFormat = new SimpleDateFormat(FrameTimeUtil.FMT_DEFAULT);
			dateFormat.setLenient(false);
			//true:允许输入空值，false:不能为空值
			binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
		}catch(Exception e) {
			SimpleDateFormat dateFormat = new SimpleDateFormat(FrameTimeUtil.FMT_YYYY_MM_DD);
			dateFormat.setLenient(false);
			//true:允许输入空值，false:不能为空值
			binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
		}
	}
	
	/**
	 * 跳转到管理页
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/prjVersion/f-view/manager")
	public String manger(HttpServletRequest request, ModelMap modelMap,
			Integer prjId) {
		PrjInfo prjInfo = prjInfoService.get(prjId);
		modelMap.put("prjInfo", prjInfo);
		return "admin/prj/version-manager";
	}

	/**
	 * 分页获取信息
	 * @return
	 */
	@RequestMapping(value = "/prjVersion/f-json/pageQuery")
	@ResponseBody
	public void pageQuery(HttpServletRequest request, HttpServletResponse response,
			PrjVersion prjVersion) {
		ResponseFrame frame = null;
		try {
			frame = prjVersionService.pageQuery(prjVersion);
		} catch (Exception e) {
			LOGGER.error("分页获取信息异常: " + e.getMessage(), e);
			frame = new ResponseFrame(ResponseCode.FAIL);
		}
		writerJson(response, frame);
	}

	/**
	 * 跳转到编辑页[包含新增和编辑]
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/prjVersion/f-view/edit")
	public String edit(HttpServletRequest request, ModelMap modelMap, Integer prjId, String version) {
		if(prjId != null) {
			modelMap.put("prjVersion", prjVersionService.get(prjId, version));
		}
		List<PrjVersion> versions = prjVersionService.findByPrjId(prjId);
		List<KvEntity> list = new ArrayList<KvEntity>();
		for (PrjVersion v : versions) {
			list.add(new KvEntity(v.getVersion(), v.getVersion()));
		}
		modelMap.put("list", list);
		return "admin/prj/version-edit";
	}

	/**
	 * 从git生成发布包
	 * @return
	 */
	@RequestMapping(value = "/prjVersion/f-json/gitCreateDeploy")
	@ResponseBody
	public void gitCreateDeploy(HttpServletRequest request, HttpServletResponse response,
			String localRepoPath, String remoteRepoUri, String branchName, String gitUsername, String gitPassword,
			String pomPath, String mavenHomePath, String deployPackage) {
		ResponseFrame frame = new ResponseFrame();
		try {
			LOGGER.info("从git远程地址" + remoteRepoUri + "生成部署包中...");
			JGitUtil git = new JGitUtil(localRepoPath, remoteRepoUri, branchName, gitUsername, gitPassword);
			boolean checkout = git.checkout();
			if (!checkout) {
				frame.setCode(-100);
				frame.setMessage("从" + remoteRepoUri + "下载代码到服务器的本地仓库" + localRepoPath + "出错了");
				writerJson(response, frame);
				return;
			}
			LOGGER.info("从git远程地址" + remoteRepoUri + " checkout成功!");
			boolean pull = git.pull();
			if (!pull) {
				frame.setCode(-110);
				frame.setMessage("从" + remoteRepoUri + "拉取代码到本地" + localRepoPath + "出错了");
				writerJson(response, frame);
				return;
			}
			LOGGER.info("从git远程地址" + remoteRepoUri + " pull成功!");
			// Maven生成打包
			//String pomPath = "D:\\data\\monitor\\project\\spider-server\\pom.xml";
			//String mavenHomePath = "C:\\Users\\Administrator\\MySoft\\apache-maven-3.0.1";
			List<String> commands = new ArrayList<String>();
			commands.add("clean");
			commands.add("install");
			LOGGER.info("执行Maven的pom.xml中...");
			List<String> pomPathList = FrameStringUtil.toArray(pomPath, ";");
			int num = 1;
			for (String pom : pomPathList) {
				frame = MavenUtil.execute(pom, mavenHomePath, commands);
				if (ResponseCode.SUCC.getCode() != frame.getCode().intValue()) {
					frame.setMessage("执行Maven的pom.xml(" + pom + ")失败!");
					writerJson(response, frame);
					return;
				}
				LOGGER.info("执行Maven的pom.xml(" + pom + ")成功[" + num + "/" + pomPathList.size() + "]!");
				num ++;
			}
			LOGGER.info("执行Maven打包命令成功");
			// 将生成的部署包复制到可以下载的项目的路径
			Integer type = SysFileType.PRJ.getCode();
			String fileExt = deployPackage.substring(deployPackage.lastIndexOf(".") + 1, deployPackage.length());
			Long dateStr = System.currentTimeMillis();
			String dateDir = FrameTimeUtil.parseString(FrameTimeUtil.getTime(), FrameTimeUtil.FMT_YYYY_MM_DD);
			String sysName = dateStr + new Random().nextInt(1000) + "." + fileExt;
			String url = type + "/" + dateDir + "/" + sysName;
			
			String savePath = SysFileUtil.getUploadFileDir();
			String newFilePath = type + File.separator + dateDir + File.separator;
			FrameFileUtil.createDir(savePath + File.separator + newFilePath);
			FrameFileUtil.copyFile(deployPackage, savePath + File.separator + newFilePath + sysName);
			LOGGER.info("将Maven打包的部署包成功拷贝到可下载文件的目录!");
			
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("url", url);
			frame.setBody(data);
			frame.setSucc();
			LOGGER.info("从git远程地址" + remoteRepoUri + "生成部署包成功!");
		} catch (Exception e) {
			LOGGER.error("保存异常: " + e.getMessage(), e);
			frame = new ResponseFrame(ResponseCode.FAIL);
		}
		writerJson(response, frame);
	}
	/**
	 * 保存
	 * @return
	 */
	@RequestMapping(value = "/prjVersion/f-json/save")
	@ResponseBody
	public void save(HttpServletRequest request, HttpServletResponse response,
			PrjVersion prjVersion) {
		ResponseFrame frame = null;
		try {
			SysUser user = getSessionUser(request);
			prjVersion.setUserId(user.getUserId());
			frame = prjVersionService.saveOrUpdate(prjVersion);
		} catch (Exception e) {
			LOGGER.error("保存异常: " + e.getMessage(), e);
			frame = new ResponseFrame(ResponseCode.FAIL);
		}
		writerJson(response, frame);
	}
	
	/**
	 * 删除
	 * @return
	 */
	@RequestMapping(value = "/prjVersion/f-json/delete")
	@ResponseBody
	public void delete(HttpServletRequest request, HttpServletResponse response,
			Integer prjId, String version) {
		ResponseFrame frame = null;
		try {
			frame = prjVersionService.delete(prjId, version);
		} catch (Exception e) {
			LOGGER.error("删除异常: " + e.getMessage(), e);
			frame = new ResponseFrame();
			frame.setCode(ResponseCode.FAIL.getCode());
		}
		writerJson(response, frame);
	}
}
